import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { View, Image, Text, Button } from '@tarojs/components';
import { sourceUrl } from '@/config';
import pencil from '@/orderSubPack/images/giftCard/pencil.png';
import noInvoice from '@/orderSubPack/images/giftCard/noInvoice.png';
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro';

import './index.scss';

const InvoiceAssistant = ({ dispatch, invoiceListData, invoiceAllListData }) => {
  const { router } = getCurrentInstance();
  const { params = {} } = router;
  const [current, setCurrent] = useState(true);
  // const [index, setIdex] = useState();
  useDidShow(() => {
    let pages = Taro.getCurrentPages();
    let curPage = pages[pages.length - 1];
    if (curPage.data.needRefreash) {
      curPage.setData({ needRefreash: false });
      dispatch({
        type: 'invoiceAssistant/invoiceListModel',
        payload: { page: 1, pageSize: 10 },
      });
    }
  });
  useEffect(() => {
    if (params.tab === 'title') {
      setCurrent(false);
    }
  }, [params.tab]);
  useEffect(() => {
    dispatch({
      type: 'invoiceAssistant/invoiceListModel',
      payload: { page: 1, pageSize: 10 },
    });
  }, []);
  useEffect(() => {
    dispatch({
      type: 'invoiceAssistant/invoiceAllListModel',
      payload: { page: 1, pageSize: 10 },
    });
  }, []);
  const handleClick = (flag) => {
    setCurrent(flag);
  };
  const seeDetails = (id) => {
    Taro.navigateTo({
      url: '/orderSubPack/invoiceManagement/invoiceDetails/index?id=' + id,
    });
  };
  const changeRadio = (val) => {
    dispatch({ type: 'productCar/setInvoiceSelected', payload: val });
    // setIdex(val);
    if (params.from !== 'mine')
      Taro.navigateBack({
        delta: 1, // 返回上一级页面。
      });
  };

  const addInvoiceHead = () => {
    Taro.navigateTo({
      url: '/orderSubPack/invoiceManagement/addInvoiceHeader/index',
    });
  };
  const editInvoiceHead = (record) => {
    const jsonObj = encodeURI(JSON.stringify(record));
    Taro.navigateTo({
      url: '/orderSubPack/invoiceManagement/addInvoiceHeader/index?type=2&jsonObj=' + jsonObj,
    });
  };
  const invoiceList = () => {
    const children = [];
    if (!invoiceAllListData) {
      return null;
    }
    const arr = invoiceAllListData;
    if (arr.length === 0) {
      children.push(
        <View className="bulletLayer">
          <Image src={noInvoice} mode="widthFix" className="noInvoice" />
          {/* <Text className="textDown">暂无发票信息</Text> */}
        </View>,
      );
    } else {
      arr.map((item) => {
        children.push(
          <View className="listView" key={item.id} onClick={() => seeDetails(item.id)}>
            <View className="flex-row-spaceBetween-center bold black085">
              <View className="txt30">{item?.merchantList[0]?.merchantName || ''}</View>
              <View className={'txt26 ' + (item.status == 4 ? 'red' : '')}>{item.statusDesc}</View>
            </View>
            <View className="flex-row img">
              {item?.mediaUrlList?.length > 0 &&
                item.mediaUrlList.map((url) => (
                  <Image
                    src={url.indexOf('http') === 0 ? url : sourceUrl + url}
                    className="zebra-line"
                  />
                ))}
              {item?.mediaUrlList?.length == 1 && (
                <View className="txt26 textUp">
                  {item?.productDetailResponseList[0]?.productName}
                </View>
              )}
            </View>
            <View className="flex-row-spaceBetween-center contentPerson">
              <View className="flex-column">
                <Text className="txt26 black085">
                  {item?.invoiceTypeName}
                  -商品明细-
                  {item?.titleTypeName}
                </Text>
                <Text className="txt22 black05 mt5">抬头名称：{item.title}</Text>
              </View>
              <View className="txt34 bold black085">¥{item.totalPrice.toFixed(2)}</View>
            </View>
            <View className="flex-row-end mt30 end">
              <View className="flex-row-center-center btn">
                查看详情
              </View>
            </View>
          </View>,
        );
      });
    }
    return children;
  };
  const invoiceListHeard = () => {
    if (!invoiceListData) {
      return null;
    }
    const children = [];
    const arr = invoiceListData;
    arr.map((item) => {
      children.push(
        <View className="flex-row-spaceBetween-center boxHeard" key={item.id}>
          <View className="flex-column leftbox" onClick={() => changeRadio(item)}>
            <View className="txt32 bold txtDot">{item.title}</View>
            {item.taxpayerNum && (
              <View className="txt28 gray textDown">纳税人识别号：{item.taxpayerNum}</View>
            )}
            {item.mobile && <View className="txt28 gray textDown">手机号：{item.mobile}</View>}
          </View>
          <View className="flex-row-end-center rightbox" onClick={() => editInvoiceHead(item)}>
            <Image src={pencil} className="mallLogo" />
          </View>
        </View>,
      );
    });
    return children;
  };
  return (
    <View className="invoiceAssistantStyle">
      <View className="header">
        <View className="textBox">
          <Text className={current ? 'text active' : 'text'} onClick={() => handleClick(true)}>
            全部发票
          </Text>
          <View className={current ? 'activeLine customePageBackgroundStyle' : ''}></View>
        </View>
        <View className="textBox">
          <Text className={!current ? 'text active' : 'text'} onClick={() => handleClick(false)}>
            抬头管理
          </Text>
          <View className={!current ? 'activeLine customePageBackgroundStyle' : ''}></View>
        </View>
      </View>
      <View className={'listViewWrap ' + (!current ? 'bottomH' : '')}>
        {current ? invoiceList() : invoiceListHeard()}
      </View>
      {!current && (
        <View className="flex-row-center-center footer">
          <Button className="btn-blueNew customePageBackgroundStyle" onClick={addInvoiceHead}>
            添加发票抬头
          </Button>
        </View>
      )}
    </View>
  );
};
export default connect(({ invoiceAssistant }) => ({
  invoiceListData: invoiceAssistant.invoiceListData,
  invoiceAllListData: invoiceAssistant.invoiceAllListData,
}))(InvoiceAssistant);
